<?php

class VideoController extends FrontEndController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('indexGroup','indexEvent', 'view','viewGroup', 'viewEvent', 'index', 'create', 'createPopup', 'createGroup','createEvent', 'update','updateGroup','updateEvent', 'admin','adminGroup','adminEvent', 'deleteVideo', 'deletecomment', 'insertcomment', 'insertcommentlike', 'deletecommentlike', 'share'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	// add comment
	public function actionInsertComment()
	{
		//if (Yii::app()->request->isAjaxRequest) {
			$data = array();
	
			if(isset($_POST['text'])){
				$data['text'] = $_POST['text'];
			}else{
				$data['text'] = '';
			}
			 
			if(isset($_GET['id'])){
				$data['id'] = $_GET['id'];
			}else{
				$data['id'] = 0;
			}
	
			if(isset($_GET['parent_id'])){
				$data['parent_id'] = $_GET['parent_id'];
			}else{
				$data['parent_id'] = 0;
			}
	
			if($data['id']){
				$make = new VideoComments;
				$make->text = $data['text'];
				$make->video_user_id = $data['id'];
				$make->user_id = Yii::app()->user->id;
				$make->parent_id = $data['parent_id'];
				$make->crdate = date("Y-m-d H:i:s");
	
				$make->save();
				
				$data['comment_id'] =  $make->getPrimaryKey();
				$user_info = Users::model()->findByPk(Yii::app()->user->id);

				$email_to = VideoUser::model()->findByPk( $data['id'] );
				$email_to = $email_to->user;
				
				if( ($email_to->comment_notification == 1) && ($email_to->last_visit < date("Y-m-d H:i:s", time() - 15*60)) ) 
				{
					Yii::app()->getModule('email');
					$email = new Email;
					$email->from = $user_info->email;
					$email->layout = 'common';
					$email->type = 'text/html';
					$email->to = $email_to->email;
					$email->view = 'main';
					$email->send(array('header' => 'Новый коментарий',
						'content' => $email_to->full_name . ', вы получили новое сообещение от '
							. $user_info->full_name . '. Получено '
							. Yii::app()->dateFormatter->formatDateTime(date("Y-m-d H:i:s"), 'long','short')
					));
					//print_r($email);
				}
	
				
				$data['user'] = array(
					'name' => $user_info->full_name,
					'id' => $user_info->id,
					'avatar' => $user_info->avatar
				);
				
				$this->renderPartial('_newComment',array(
					'comment'=>$data
				));
			}
		//}else{
		//	$this->redirect(Yii::app()->createUrl('video/view', array('id'=>$data['id'])));
		//}
	}
	// delete comment
	public function actionDeleteComment(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['comment_id'])){
				VideoComments::model()->deleteAll("id = '" . $_GET['comment_id'] . "'");
			}
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}
	}
	// comment like add
	public function actionInsertCommentLike(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['video_id'])){
				$make = new VideoLikes;
				$make->video_user_id = $_GET['video_id'];
				$make->user_id = Yii::app()->user->id;
				$make->save();
	
				$video_like_id = $make->getPrimaryKey();
				 
				$data['href_dislike'] = Yii::app()->createUrl('video/deletecommentlike', array('video_id'=>$_GET['video_id'], 'video_like_id'=>$video_like_id));
				 
				echo CJSON::encode($data);
			}
		}else{
			$this->redirect(Yii::app()->createUrl('video/view', array('id'=>$_GET['video_id'])));
		}
	}
	
	// comment like delete
	public function actionDeleteCommentLike(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['video_like_id'])){
				VideoLikes::model()->deleteAll("id = '" . $_GET['video_like_id'] . "'");
	
				$data['href_like'] = Yii::app()->createUrl('video/insertcommentlike', array('video_id'=>$_GET['video_id']));
	
				echo CJSON::encode($data);
			}
		}else{
			$this->redirect(Yii::app()->createUrl('video/view', array('id'=>$_GET['video_id'])));
		}
	}
	public function actionIndex()
	{
		$user_id = isset($_GET['profile']) ? $_GET['profile']: Yii::app()->user->id;
		$video=VideoUser::model()->findAll(array(
			'order'=> 'crdate DESC',
			'condition'=>'user_id=:user_id AND status=1',
			'params'=>array(':user_id'=>$user_id)
		));
		$this->render('index',array(
			'data'=>$video,
		));
	}

	public function actionIndexGroup($group)
	{
		$checkOwner = Groups::model()->findByPk($group)->checkAdmin;
		$video=VideoUser::model()->findAll(array(
			'order'=> 'crdate DESC',
			'condition'=>'group_id=:group_id',
			'params'=>array(':group_id'=>$group)
		));
		$this->render('indexGroup',array(
			'data'=>$video,
			'checkOwner'=>$checkOwner,
		));
	}
	public function actionIndexEvent($event)
	{
		$checkOwner = Events::model()->findByPk($event)->group->checkAdmin;
		$video=VideoUser::model()->findAll(array(
			'order'=> 'crdate DESC',
			'condition'=>'event_id=:event_id',
			'params'=>array(':event_id'=>$event)
		));
		$this->render('indexEvent',array(
			'data'	=>	$video,
			'checkOwner'=>$checkOwner,
		));
	}

	public function actionView($id)
	{	
		$this->renderPartial('viewAjax',array(
			'data'=>VideoUser::model()->findByPk($id),
		));
	}

	public function actionViewGroup($id)
	{	
		$data = VideoUser::model()->findByPk($id);
		$checkVideo = VideoUser::model()->find(
			'video_id=:video_id AND user_id=:user_id',
			array('video_id'=>$data->video_id, 'user_id'=>Yii::app()->user->id)
		);
		$this->renderPartial('viewAjaxGroup',array(
			'data'=>$data,
			'checkVideo'=>$checkVideo,
		));

	}
	public function actionViewEvent($id)
	{	
		$data = VideoUser::model()->findByPk($id);
		$checkVideo = VideoUser::model()->find(
			'video_id=:video_id AND user_id=:user_id',
			array('video_id'=>$data->video_id, 'user_id'=>Yii::app()->user->id)
		);
		$this->renderPartial('viewAjaxEvent',array(
			'data'=>$data,
			'checkVideo'=>$checkVideo,
		));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$user_id = isset($_GET['profile']) ? $_GET['profile']: Yii::app()->user->id;
		$video=VideoUser::model()->findAll(array(
				'order'=> 'crdate DESC',
				'condition'=>'user_id=:user_id AND status=1',
				'params'=>array(':user_id'=>$user_id)
		));
		$this->render('admin',array(
				'model'=>$video,
		));
	}
	public function actionAdminGroup()
	{
		$video=VideoUser::model()->findAll(array(
				'order'=> 'crdate DESC',
				'condition'=>'group_id=:group_id',
				'params'=>array(':group_id'=>$_GET['group'])
		));
		$this->render('adminGroup',array(
				'model'=>$video,
		));
	}
	public function actionAdminEvent()
	{
		$video=VideoUser::model()->findAll(array(
				'order'=> 'crdate DESC',
				'condition'=>'event_id=:event_id',
				'params'=>array(':event_id'=>$_GET['event'])
		));
		$this->render('adminEvent',array(
				'model'=>$video,
		));
	}
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Video;
		if(isset($_POST['Video']))
		{
			$url = $_POST['Video']['url'];
			if(strpos($url, 'http://youtube.com') !== false || strpos($url, 'http://youtu.be/') !== false || strpos($url, 'http://rutube.ru') !== false || strpos($url, 'http://vimeo.com') !== false || 
				strpos($url, 'http://www.youtube.com') !== false || strpos($url, 'http://www.youtu.be/') !== false || strpos($url, 'http://www.rutube.ru') !== false || strpos($url, 'http://www.vimeo.com') !== false)
			{
				$_POST['Video']['code'] = VideoCreate::getVideoCode($url);
				$_POST['Video']['user_id'] = Yii::app()->user->id;
				$model->attributes=$_POST['Video'];
				if($model->validate())
				{
					$model->save();
					$make = new VideoUser;
					$make->video_id = $model->id;
					$make->user_id = Yii::app()->user->id;
					$make->name = $_POST['Video']['name'];
					$make->crdate = date("Y-m-d H:i:s");
					$make->status = 1;
					$make->save();
					$this->redirect(Yii::app()->createUrl('video/index', array('profile'=>Yii::app()->request->getParam('profile'))));
				}
			} 
			else
			{
				$model->addError('url','Вы используете не правильную ссылку');
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	public function actionCreatePopup()
	{
		if(isset($_POST['Video']))
		{
			$url = $_POST['Video']['url'];
			if(strpos($url, 'http://youtube.com') !== false || strpos($url, 'http://youtu.be/') !== false || strpos($url, 'http://rutube.ru') !== false || strpos($url, 'http://vimeo.com') !== false ||
					strpos($url, 'http://www.youtube.com') !== false || strpos($url, 'http://www.youtu.be/') !== false || strpos($url, 'http://www.rutube.ru') !== false || strpos($url, 'http://www.vimeo.com') !== false)
			{
				$model=new Video;
				$_POST['Video']['name'] = $_POST['Video']['url'];
				$_POST['Video']['code'] = VideoCreate::getVideoCode($url);
				$_POST['Video']['user_id'] = Yii::app()->user->id;
				$model->attributes=$_POST['Video'];
				if($model->validate())
				{
					$model->save();
					$make = new VideoUser;
					$make->video_id = $model->id;
					$make->user_id = Yii::app()->user->id;
					$make->name = $_POST['Video']['name'];
					$make->crdate = date("Y-m-d H:i:s");
					$make->status = 0;
					$make->save();
					$preview = VideoPreview::getVideoPreview($_POST['Video']['code']);
					echo "<div class='one_image'>".
					"<div class='image_x_wrap'><div class='image_x'></div></div>".
					"<img width='180' src='". $preview . "'/>".
					//"<div class='name'>".$make->name."</div>".
					"<input type='hidden' name='videos[]' value='". $model->id ."' class='videos' />".
					"</div>";
				}
			}
			else
			{
				echo 'Вы используете не правильную ссылку';
			}
		} else {
			echo 'Ошибка';
		}
	}
	public function actionCreateGroup($group)
	{
		$model=new Video;
		if(isset($_POST['Video']))
		{
			$url = $_POST['Video']['url'];
			if(strpos($url, 'http://youtube.com') !== false || strpos($url, 'http://youtu.be/') !== false || strpos($url, 'http://rutube.ru') !== false || strpos($url, 'http://vimeo.com') !== false || 
				strpos($url, 'http://www.youtube.com') !== false || strpos($url, 'http://www.youtu.be/') !== false || strpos($url, 'http://www.rutube.ru') !== false || strpos($url, 'http://www.vimeo.com') !== false)
			{
				$_POST['Video']['code'] = VideoCreate::getVideoCode($url);
				$_POST['Video']['user_id'] = Yii::app()->user->id;
				$model->attributes=$_POST['Video'];
				if($model->validate())
				{
					$model->save();
					$make = new VideoUser;
					$make->video_id = $model->id;
					$make->group_id = $group;
					$make->name = $_POST['Video']['name'];
					$make->crdate = date("Y-m-d H:i:s");
					$make->save();
					$this->redirect(Yii::app()->createUrl('video/indexGroup', array('group'=>Yii::app()->request->getParam('group'))));
				}
			} 
			else
			{
				$model->addError('url','Вы используете не правильную ссылку');
			}
		}

		$this->render('createGroup',array(
			'model'=>$model,
		));
	}

	public function actionCreateEvent($event)
	{
		$model=new Video;
		if(isset($_POST['Video']))
		{
			$url = $_POST['Video']['url'];
			if(strpos($url, 'http://youtube.com') !== false || strpos($url, 'http://youtu.be/') !== false || strpos($url, 'http://rutube.ru') !== false || strpos($url, 'http://vimeo.com') !== false || 
				strpos($url, 'http://www.youtube.com') !== false || strpos($url, 'http://www.youtu.be/') !== false || strpos($url, 'http://www.rutube.ru') !== false || strpos($url, 'http://www.vimeo.com') !== false)
			{
				$_POST['Video']['code'] = VideoCreate::getVideoCode($url);
				$_POST['Video']['user_id'] = Yii::app()->user->id;
				$model->attributes=$_POST['Video'];
				if($model->validate())
				{
					$model->save();
					$make = new VideoUser;
					$make->video_id = $model->id;
					$make->event_id = $event;
					$make->name = $_POST['Video']['name'];
					$make->crdate = date("Y-m-d H:i:s");
					$make->save();
					$this->redirect(Yii::app()->createUrl('video/indexEvent', array('event'=>Yii::app()->request->getParam('event'))));
				}
			} 
			else
			{
				$model->addError('url','Вы используете не правильную ссылку');
			}
		}

		$this->render('createEvent',array(
			'model'=>$model,
		));
	}

	public function actionShare()
	{
		if(isset($_GET['id'])){
			$model=VideoUser::model()->findByPk($_GET['id']);
			
			$make = new VideoUser;
			$make->video_id = $model->video_id;
			$make->user_id = Yii::app()->user->id;
			$make->name = $model->name;
			$make->description = $model->description;
			$make->crdate = date("Y-m-d H:i:s");
			$make->status = 1;
			$make->save();
		}
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=VideoUser::model()->findByPk($id);
		if(isset($_POST['VideoUser']))
		{
			$model->attributes=$_POST['VideoUser'];
			if($model->save())
				$this->redirect(array('index','profile'=>$model->user_id));
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionUpdateGroup($id)
	{
		$model=VideoUser::model()->findByPk($id);
		if(isset($_POST['VideoUser']))
		{
			$model->attributes=$_POST['VideoUser'];
			if($model->save())
				$this->redirect(array('indexGroup','group'=>$model->group_id));
		}
		$this->render('updateGroup',array(
			'model'=>$model,
		));
	}
	
	public function actionUpdateEvent($id)
	{
		$model=VideoUser::model()->findByPk($id);
		if(isset($_POST['VideoUser']))
		{
			$model->attributes=$_POST['VideoUser'];
			if($model->save())
				$this->redirect(array('indexEvent','event'=>$model->event_id));
		}
		$this->render('updateEvent',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDeleteVideo($id)
	{
		$model = VideoUser::model()->findByPk($id);
		$model->status = 0;
		$model->save();
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		//if(!isset($_GET['ajax']))
		//$this->redirect(Yii::app()->createUrl('video/admin', array('profile'=>Yii::app()->request->getParam('profile'))));
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Video::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
